package com.zivwu.library;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.components.RxActivity;
import com.zivwu.library.dao.bean.Photo;
import com.zivwu.library.dao.local.cache.DiskLruCache;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Provider;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class MainActivity extends RxActivity {

    @Bind(R.id.sink)
    Button sink;
    @Bind(R.id.source)
    Button source;

    @Bind(R.id.imageview2)
    ImageView imageView2;
    private DiskLruCache diskLruCache;
    private ArrayList<Map.Entry<String, List<Photo>>> photos;
    private Photo photo;
    private List<Photo> value;
    private FileComponent daggerFileComponent;


    @Inject
    AppModule appModule;


    @Inject
    Provider<Uri> uri;

    Uri imageUri;
    Uri oldUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Logger.addLogAdapter(new AndroidLogAdapter());
        FileComponent build = DaggerFileComponent.builder().appModule(new AppModule(this)).build();
        build.inject(this);
//        daggerFileComponent = DaggerFileComponent.builder()
//                .appModule(new AppModule(this))
//                .build();

    }



    int i = 10;

    @OnClick({R.id.sink, R.id.source, R.id.clock_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sink:
                PhotoPicker.builder().start(this);
                break;
            case R.id.source:
                PhotoPicker.builder().start(this);
                break;

            case R.id.clock_btn:
                imageUri=uri.get();
                oldUri= uri.get();
                PhotoPicker.builder()
                        .setExtraOutput(imageUri)
                        .setDataAndType(oldUri)
                        .start(this);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
//            final Uri resultUri = UCrop.getOutput(data);
//            GlideApp.with(this)
//                    .asBitmap()
//                    .circleCrop()
//                    .load(resultUri)
//                    .into(imageView2);
//            Logger.d(resultUri.toString());
//        } else if (resultCode == UCrop.RESULT_ERROR) {
//            final Throwable cropError = UCrop.getError(data);
//        }
//        data.getData();
        if (PhotoPicker.RequestCode.getMode(requestCode)==PhotoPicker.RequestCode.CAMERA&&
                PhotoPicker.RequestCode.getCode(requestCode)==PhotoPicker.REQUEST_CODE){
            if (resultCode== Activity.RESULT_OK){
                // TODO: 2017/9/25 0025 数据获取成功
            }else{
                // TODO: 2017/9/25 0025 失败
            }
        }
        if (PhotoPicker.RequestCode.getMode(requestCode)==PhotoPicker.RequestCode.CROP&&
                PhotoPicker.RequestCode.getCode(requestCode)==PhotoPicker.REQUEST_CODE)
        Glide.with(this)
                .load(imageUri)
                .into(imageView2);
    }


    public void startPhotoZoom( Uri inUri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(inUri, "image/*");
        //下面这个crop = true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        //该参数可以不设定用来规定裁剪区的宽高比
        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);
        //该参数设定为你的imageView的大小
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        //是否返回bitmap对象
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出图片的格式
        intent.putExtra("noFaceDetection", true); // 头像识别
        startActivityForResult(intent,
//                3
                PhotoPicker.RequestCode.makeRequestCode(requestCode, PhotoPicker.RequestCode.CROP)
        );
    }

    private void testPost() {
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)
//                        .addNetworkInterceptor()
                .connectTimeout(15, TimeUnit.SECONDS).build();
        RequestBody formBody = new FormBody.Builder()
                .add("mobile", "18662525445")
                .build();
        final Request request = new Request.Builder()
                .url("http://test.58lianjiao.com/" + "User/getRegisterSms")
                .post(formBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Logger.d("onFailure");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
//                        Logger.d(response.body().string());
            }
        });
    }

    String path = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1504257613841&di=25b78a3227d272dcf578a0267032d1fa&imgtype=0&src=http%3A%2F%2Fpic24.nipic.com%2F20120922%2F3709274_232951575000_2.jpg";

    //当sd卡可用时存放在sd卡的cache目录下，否则存放在包下
    public File getDiskCacheDir(Context context, String uniqueName) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);


    }

    private void testInstance() throws Exception {
        Class<TestClass> classClass = TestClass.class;

        String name = classClass.getName();
        Class<?> aClass = Class.forName(name);

        Constructor<?> constructor = aClass.getConstructor(int.class, String.class);

//        TestClass o = (TestClass) constructor.newInstance(1, "asdf2");
//        o.printAll();
        Gson gson = new Gson();
        String json = " {\n" +
                "            \"id\":\"123123\",\n" +
                "            \"sfj\":\"sfj123123\",\n" +
                "            \"email\":\"aaaa\"\n" +
                "        }";
        gson.fromJson(json, TestClass.class);

    }


    public static class TestClass {
        private int id;
        private String sfj;

        public TestClass(int l, String sfj) {
            this.id = l;
            this.sfj = sfj;
        }


        private void printAll() {
            Logger.d(id + "sfj");
        }
    }

}
